package cn.exrick.xboot.common.utils;

import cn.hutool.core.util.RandomUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class ZOSUtil {

    private static AmazonS3 amazonS3;

    private static String bucketName;

    private static String parentDir;

    private static String endPoint;


    @Autowired
    public void setObsClient(AmazonS3 amazonS3) {
        ZOSUtil.amazonS3 = amazonS3;
    }
    @Value("${ctyun.obs.bucket-name}")
    public void setBucketName(String bucketName) {
        ZOSUtil.bucketName = bucketName;
    }
    @Value("${ctyun.obs.parentDir}")
    public void setParentDir(String parentDir) {
        ZOSUtil.parentDir = parentDir;
    }

    @Value("${ctyun.obs.endpoint}")
    public void setEndPoint(String endPoint) {
        ZOSUtil.endPoint = endPoint;
    }

    public static String uploadFile(MultipartFile multipartFile, String objectKey) throws Exception {
        // 获取文件扩展名
        String extension = objectKey.substring(objectKey.lastIndexOf("."));
        // 生成8位随机字符串作为新文件名
        String randomFileName = RandomUtil.randomString(8) + extension;
        PutObjectRequest request = new PutObjectRequest(bucketName,  parentDir + "/" + randomFileName, multipartFile.getInputStream(), null);
        request.setCannedAcl(CannedAccessControlList.PublicRead);
        PutObjectResult result = amazonS3.putObject(request);

        return endPoint + "/"  + bucketName  + "/"  + parentDir + "/" + randomFileName;
    }
}
